package com.anonymous.community;

import android.os.Bundle;
import android.os.CountDownTimer;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.anonymous.community.api.ApiClient;
import com.anonymous.community.api.ApiService;
import com.anonymous.community.api.model.GenericResponse;
import com.anonymous.community.api.model.ResetPasswordRequest;
import com.anonymous.community.api.model.SendCodeRequest;
import com.anonymous.community.databinding.ActivityForgotPasswordBinding;
import com.anonymous.community.ui.base.BaseActivity;
import com.tencent.bugly.crashreport.CrashReport;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * 忘记密码Activity - 根据API v3.0.0文档
 * 流程：
 * 1. 发送验证码 POST /v1/api/auth/send-code (purpose="reset_password")
 * 2. 重置密码 POST /v1/api/auth/reset-password
 */
public class ForgotPasswordActivity extends BaseActivity {

    private ActivityForgotPasswordBinding binding;
    private ApiService apiService;
    private CountDownTimer countDownTimer;
    private boolean isCountingDown = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityForgotPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        apiService = ApiClient.getApiService();

        setupViews();
    }

    private void setupViews() {
        // 发送验证码按钮
        binding.btnSendCode.setOnClickListener(v -> sendVerificationCode());
        
        // 重置密码按钮
        binding.btnResetPassword.setOnClickListener(v -> resetPassword());
        
        // 返回登录
        binding.btnBack.setOnClickListener(v -> finish());
    }

    /**
     * 发送验证码
     */
    private void sendVerificationCode() {
        String email = binding.etEmail.getText().toString().trim();

        if (TextUtils.isEmpty(email)) {
            binding.tilEmail.setError("请输入注册邮箱");
            return;
        }

        if (!isValidEmail(email)) {
            binding.tilEmail.setError("请输入有效的邮箱地址");
            return;
        }

        binding.tilEmail.setError(null);
        hideErrorMessage();

        // 禁用按钮
        binding.btnSendCode.setEnabled(false);

        // 创建发送验证码请求
        SendCodeRequest request = new SendCodeRequest(email, "reset_password");
        
        apiService.sendCode(request).enqueue(new Callback<GenericResponse>() {
            @Override
            public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                if (response.isSuccessful() && response.body() != null) {
                    Toast.makeText(ForgotPasswordActivity.this, "验证码已发送到您的邮箱", Toast.LENGTH_SHORT).show();
                    startCountDown();
                } else {
                    String errorMessage = extractErrorMessage(response);
                    if (TextUtils.isEmpty(errorMessage)) {
                        errorMessage = "发送验证码失败，请稍后重试";
                    }
                    showErrorMessage(errorMessage);
                    binding.btnSendCode.setEnabled(true);
                }
            }

            @Override
            public void onFailure(Call<GenericResponse> call, Throwable t) {
                showErrorMessage("网络连接失败，请检查网络设置");
                binding.btnSendCode.setEnabled(true);
            }
        });
    }

    /**
     * 重置密码
     */
    private void resetPassword() {
        String email = binding.etEmail.getText().toString().trim();
        String code = binding.etVerificationCode.getText().toString().trim();
        String newPassword = binding.etNewPassword.getText().toString().trim();
        String confirmPassword = binding.etConfirmNewPassword.getText().toString().trim();

        // 验证输入
        if (TextUtils.isEmpty(email)) {
            binding.tilEmail.setError("请输入邮箱");
            return;
        }

        if (!isValidEmail(email)) {
            binding.tilEmail.setError("请输入有效的邮箱地址");
            return;
        }

        if (TextUtils.isEmpty(code)) {
            binding.tilVerificationCode.setError("请输入验证码");
            return;
        }

        if (TextUtils.isEmpty(newPassword)) {
            binding.tilNewPassword.setError("请输入新密码");
            return;
        }

        // 密码至少6个字符
        if (newPassword.length() < 6) {
            binding.tilNewPassword.setError("密码至少需要6个字符");
            return;
        }

        if (!TextUtils.equals(newPassword, confirmPassword)) {
            binding.tilConfirmNewPassword.setError("两次输入的密码不一致");
            return;
        }

        clearErrors();
        hideErrorMessage();
        showLoading(true);

        // 创建重置密码请求
        ResetPasswordRequest request = new ResetPasswordRequest(email, code, newPassword);

        apiService.resetPassword(request).enqueue(new Callback<GenericResponse>() {
            @Override
            public void onResponse(Call<GenericResponse> call, Response<GenericResponse> response) {
                showLoading(false);
                if (response.isSuccessful() && response.body() != null) {
                    // 添加密码重置成功事件统计
                    CrashReport.postCatchedException(new Exception("Event: Password Reset Success"));
                    
                    Toast.makeText(ForgotPasswordActivity.this, "密码重置成功", Toast.LENGTH_SHORT).show();
                    finish();
                } else {
                    String errorMessage = extractErrorMessage(response);
                    if (TextUtils.isEmpty(errorMessage)) {
                        errorMessage = "重置失败，请检查验证码和密码";
                    }
                    showErrorMessage(errorMessage);
                }
            }

            @Override
            public void onFailure(Call<GenericResponse> call, Throwable t) {
                showLoading(false);
                showErrorMessage("网络连接失败，请检查网络设置");
            }
        });
    }

    /**
     * 开始倒计时（60秒）
     */
    private void startCountDown() {
        isCountingDown = true;
        binding.btnSendCode.setEnabled(false);
        
        countDownTimer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long millisUntilFinished) {
                binding.btnSendCode.setText(String.format("%d秒后重试", millisUntilFinished / 1000));
            }

            @Override
            public void onFinish() {
                binding.btnSendCode.setText("发送验证码");
                binding.btnSendCode.setEnabled(true);
                isCountingDown = false;
            }
        }.start();
    }

    /**
     * 验证邮箱格式
     */
    private boolean isValidEmail(String email) {
        return android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches();
    }

    private void clearErrors() {
        binding.tilEmail.setError(null);
        binding.tilVerificationCode.setError(null);
        binding.tilNewPassword.setError(null);
        binding.tilConfirmNewPassword.setError(null);
    }

    private void showLoading(boolean show) {
        binding.btnResetPassword.setEnabled(!show);
        binding.btnSendCode.setEnabled(!show && !isCountingDown);
        binding.etEmail.setEnabled(!show);
        binding.etVerificationCode.setEnabled(!show);
        binding.etNewPassword.setEnabled(!show);
        binding.etConfirmNewPassword.setEnabled(!show);
    }

    private void showErrorMessage(String message) {
        binding.tvErrorMessage.setText(message);
        binding.tvErrorMessage.setVisibility(View.VISIBLE);
    }

    private void hideErrorMessage() {
        binding.tvErrorMessage.setVisibility(View.GONE);
    }

    /**
     * 从错误响应中提取 error 字段
     */
    private String extractErrorMessage(Response<?> response) {
        try {
            if (response != null && response.errorBody() != null) {
                String raw = response.errorBody().string();
                if (!TextUtils.isEmpty(raw)) {
                    try {
                        org.json.JSONObject obj = new org.json.JSONObject(raw);
                        if (obj.has("error")) {
                            return obj.optString("error");
                        }
                    } catch (Exception jsonEx) {
                        return raw;
                    }
                }
            }
        } catch (Exception e) {
            // 忽略解析错误
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        binding = null;
    }

    @Override
    protected String getPageName() {
        return "找回密码页";
    }
}

